package junior.db.dao.mybatis.type;

import java.util.Arrays;
import java.util.Map;

public class AssociationType {
    private String field;
    private Class<?> type;
    private Class<?> collectionType;
    private Map<String, String> columnMapping;
    
    public AssociationType(String field, Class<?> type, Map<String, String> columnMapping) {
        this(field, null, type, columnMapping);
    }
    
    public AssociationType(String field, Class<?> collectionType, Class<?> type, Map<String, String> columnMapping) {
        this.field = field;
        this.type = type;
        this.collectionType = collectionType;
        this.columnMapping = columnMapping;
    }
    
    public String getField() {
        return field;
    }
    
    public void setField(String field) {
        this.field = field;
    }
    
    public Class<?> getType() {
        return type;
    }
    
    public void setType(Class<?> type) {
        this.type = type;
    }
    
    public Class<?> getCollectionType() {
        return collectionType;
    }
    
    public void setCollectionType(Class<?> collectionType) {
        this.collectionType = collectionType;
    }
    
    public Map<String, String> getColumnMapping() {
        return columnMapping;
    }
    
    public void setColumnMapping(Map<String, String> columnMapping) {
        this.columnMapping = columnMapping;
    }
    
    public String generateId(String msId, String resultTypeName) {
        StringBuilder buff = new StringBuilder();
        buff.append(msId).append("_").append(resultTypeName).append("[").append(field).append("]");
        buff.append(collectionType != null ? "_collection[" : "_[");
        if (columnMapping == null || columnMapping.isEmpty()) {
            buff.append("all]");
            return buff.toString();
        }
        String[] array = new String[columnMapping.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : columnMapping.entrySet()) {
            array[i ++] = entry.getKey() + "=" + entry.getValue();
        }
        buff.append(Arrays.hashCode(array)).append("]");
        return buff.toString();
    }
}
